import sys
import os
import re
from pathlib import Path
from PySide6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout, 
                              QHBoxLayout, QLabel, QPushButton, QProgressBar, 
                              QTextEdit, QFrame, QMessageBox, QFileDialog)
from PySide6.QtCore import Qt, Signal
from PySide6.QtGui import QFont, QDropEvent, QDragEnterEvent, QColor, QTextCursor

class DropArea(QFrame):
    """支持拖放的区域组件"""
    folder_dropped = Signal(str)
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setAcceptDrops(True)
        self.setMinimumHeight(100)
        self.setStyleSheet("""
            QFrame {
                background-color: #f0f0f0;
                border: 2px dashed #aaa;
                border-radius: 5px;
            }
            QFrame:hover {
                border-color: #666;
            }
        """)
        
        layout = QVBoxLayout(self)
        self.label = QLabel("拖放文件夹到此处\n或点击按钮选择", self)
        self.label.setAlignment(Qt.AlignCenter)
        self.label.setWordWrap(True)
        layout.addWidget(self.label)
    
    def dragEnterEvent(self, event: QDragEnterEvent):
        if event.mimeData().hasUrls():
            for url in event.mimeData().urls():
                if url.isLocalFile():
                    path = url.toLocalFile()
                    if os.path.isdir(path):
                        event.acceptProposedAction()
                        return
        event.ignore()
    
    def dropEvent(self, event: QDropEvent):
        if event.mimeData().hasUrls():
            for url in event.mimeData().urls():
                if url.isLocalFile():
                    path = url.toLocalFile()
                    if os.path.isdir(path):
                        self.folder_dropped.emit(path)
                        self.label.setText(f"已选择:\n{os.path.basename(path)}")
                        return
        event.ignore()
    
    def set_selected_folder(self, path):
        self.label.setText(f"已选择:\n{os.path.basename(path)}")

class FunctionArea(QWidget):
    """功能区域组件，每个类型的图片处理一个"""
    def __init__(self, title, prefix, replace_words, parent=None):
        super().__init__(parent)
        self.title = title
        self.prefix = prefix
        self.replace_words = replace_words
        self.selected_path = None
        
        self.init_ui()
    
    def init_ui(self):
        # 主布局
        main_layout = QVBoxLayout(self)
        main_layout.setContentsMargins(10, 10, 10, 10)
        main_layout.setSpacing(10)
        
        # 标题
        title_label = QLabel(self.title)
        font = QFont()
        font.setPointSize(12)
        font.setBold(True)
        title_label.setFont(font)
        main_layout.addWidget(title_label)
        
        # 拖放区域
        self.drop_area = DropArea()
        self.drop_area.folder_dropped.connect(self.on_folder_selected)
        main_layout.addWidget(self.drop_area)
        
        # 按钮区域
        btn_layout = QHBoxLayout()
        
        # 选择文件夹按钮
        self.select_btn = QPushButton("选择文件夹")
        self.select_btn.clicked.connect(self.select_folder)
        btn_layout.addWidget(self.select_btn)
        
        # 处理按钮
        self.process_btn = QPushButton("开始重命名")
        self.process_btn.clicked.connect(self.process_files)
        btn_layout.addWidget(self.process_btn)
        
        main_layout.addLayout(btn_layout)
        
        # 进度条
        self.progress_bar = QProgressBar()
        self.progress_bar.setValue(0)
        main_layout.addWidget(self.progress_bar)
        
        # 状态标签
        self.status_label = QLabel("等待操作...")
        self.status_label.setStyleSheet("color: blue;")
        main_layout.addWidget(self.status_label)
        
        # 日志标题
        log_label = QLabel("操作日志:")
        main_layout.addWidget(log_label)
        
        # 日志区域
        self.log_text = QTextEdit()
        self.log_text.setReadOnly(True)
        self.log_text.setMinimumHeight(100)
        main_layout.addWidget(self.log_text)
    
    def log(self, message, is_error=False):
        """添加日志信息"""
        # 修复：使用QTextCursor.End而不是小写的End
        cursor = self.log_text.textCursor()
        cursor.movePosition(QTextCursor.End)
        self.log_text.setTextCursor(cursor)
        
        if is_error:
            self.log_text.setTextColor(QColor("red"))
        else:
            self.log_text.setTextColor(QColor("black"))
            
        self.log_text.insertPlainText(message + "\n")
        self.log_text.moveCursor(QTextCursor.End)
    
    def set_status(self, message):
        """设置状态信息"""
        self.status_label.setText(message)
    
    def set_progress(self, value):
        """设置进度条"""
        self.progress_bar.setValue(value)
    
    def select_folder(self):
        """选择文件夹对话框"""
        folder_path = QFileDialog.getExistingDirectory(
            self, f"选择{self.title}文件夹", os.getcwd()
        )
        if folder_path:
            self.on_folder_selected(folder_path)
    
    def on_folder_selected(self, path):
        """处理选中的文件夹"""
        self.selected_path = path
        self.drop_area.set_selected_folder(path)
        self.set_status(f"已选择文件夹: {os.path.basename(path)}")
        self.log(f"已选择文件夹: {path}")
    
    def get_image_files(self, folder_path):
        """获取文件夹中的所有图片文件"""
        image_extensions = {'.jpg', '.jpeg', '.png', '.gif', '.webp'}
        image_files = []
        
        for filename in os.listdir(folder_path):
            file_path = os.path.join(folder_path, filename)
            if os.path.isfile(file_path):
                ext = os.path.splitext(filename)[1].lower()
                if ext in image_extensions:
                    image_files.append(file_path)
        
        return image_files
    
    def process_files(self):
        """处理文件重命名"""
        if not self.selected_path or not os.path.isdir(self.selected_path):
            QMessageBox.warning(self, "警告", "请先选择有效的文件夹")
            return
        
        try:
            # 获取所有图片文件
            image_files = self.get_image_files(self.selected_path)
            total_files = len(image_files)
            
            if total_files == 0:
                self.set_status("未找到任何图片文件")
                QMessageBox.information(self, "提示", "未找到任何图片文件")
                return
            
            self.set_status(f"准备处理 {total_files} 个图片文件...")
            self.set_progress(0)
            self.log(f"开始处理文件夹: {self.selected_path}")
            self.log(f"找到 {total_files} 个图片文件")
            
            # 尝试排序文件
            try:
                image_files.sort(key=lambda item: int(re.search(r"\d+", Path(item).resolve().stem).group()))
                self.log("已按数字顺序排序文件")
            except Exception as e:
                self.log(f"排序警告: 无法按数字排序，将使用默认顺序 - {str(e)}", is_error=True)
            
            # 重命名文件
            success_count = 0
            for index, file in enumerate(image_files, start=1):
                try:
                    file_path = Path(file).resolve()
                    directory = file_path.parent
                    old_name = file_path.name
                    suffix = file_path.suffix
                    
                    # 创建新文件名
                    new_basename = f"{self.prefix}-{index:03}"
                    for word in self.replace_words:
                        new_basename = new_basename.replace(word, "-")
                    new_name = f"{new_basename}{suffix}"
                    
                    # 重命名
                    old_full_path = os.path.join(directory, old_name)
                    new_full_path = os.path.join(directory, new_name)
                    
                    # 检查新文件名是否已存在
                    if os.path.exists(new_full_path):
                        self.log(f"跳过 {old_name}: 目标文件 {new_name} 已存在")
                        continue
                    
                    os.rename(old_full_path, new_full_path)
                    self.log(f"已重命名: {old_name} -> {new_name}")
                    success_count += 1
                    
                except Exception as e:
                    self.log(f"重命名失败 {old_name}: {str(e)}", is_error=True)
                
                # 更新进度
                progress = (index / total_files) * 100
                self.set_progress(int(progress))
            
            self.set_progress(100)
            self.set_status(f"处理完成: 成功{success_count}个，失败{total_files - success_count}个")
            QMessageBox.information(
                self, "完成", 
                f"{self.title}处理完成:\n成功{success_count}个\n失败{total_files - success_count}个"
            )
            
        except Exception as e:
            error_msg = f"处理时出错: {str(e)}"
            self.set_status(error_msg)
            self.log(error_msg, is_error=True)
            QMessageBox.critical(self, "错误", error_msg)

class ImageRenamerApp(QMainWindow):
    """主应用窗口"""
    def __init__(self):
        super().__init__()
        self.setWindowTitle("图片批量重命名工具")
        self.setGeometry(100, 100, 1200, 800)
        
        # 创建中心部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 主布局
        main_layout = QVBoxLayout(central_widget)
        main_layout.setContentsMargins(20, 20, 20, 20)
        main_layout.setSpacing(20)
        
        # 标题
        title_label = QLabel("图片批量重命名工具")
        font = QFont()
        font.setPointSize(14)
        font.setBold(True)
        title_label.setFont(font)
        title_label.setAlignment(Qt.AlignCenter)
        main_layout.addWidget(title_label)
        
        # 三个功能区域的布局
        areas_layout = QHBoxLayout()
        areas_layout.setSpacing(20)
        main_layout.addLayout(areas_layout)
        
        # 主图区域
        self.main_area = FunctionArea("主图处理区", "Main", ["主", "图", "首"])
        areas_layout.addWidget(self.main_area)
        
        # 详情图区域
        self.detail_area = FunctionArea("详情图处理区", "Detail", ["详情", "长图"])
        areas_layout.addWidget(self.detail_area)
        
        # SKU图区域
        self.sku_area = FunctionArea("SKU图处理区", "SKU", ["规格", "属性"])
        areas_layout.addWidget(self.sku_area)
        
        # 设置三个区域平分空间
        areas_layout.setStretch(0, 1)
        areas_layout.setStretch(1, 1)
        areas_layout.setStretch(2, 1)

if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = ImageRenamerApp()
    window.show()
    sys.exit(app.exec())